package com.zr.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.zr.model.UserModel;
import com.zr.service.LoginService;

/**
 * 登录验证servlet
 * @author 曾鹏
 *
 */
public class LoginController extends HttpServlet{
	LoginService ls = new LoginService();
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(req, resp);
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		req.setCharacterEncoding("utf8");
		//用户的id
		String sid = req.getParameter("tid");
		req.setCharacterEncoding("utf8");
		//用户的密码

		int ssid = 0 ;
		// 判断前台输入的账号如果不为空，则将String转换为int
	    if(null!=sid && ""!=sid && sid.length()<8) 
	    { 
			try {
				 ssid = Integer.parseInt(sid);
			} catch (NumberFormatException e) {
				// TODO: handle exception
				e.printStackTrace();
			}
	    }


		String spwt = req.getParameter("tpsw");
		//如果勾住记住我，则实现记住的功能
		if("on".equals(req.getParameter("remember"))){
			//1.生成cookie对象
			Cookie cookiesname = new Cookie("sid", sid);
			Cookie cookiepsw = new Cookie("spwt", spwt);
			//2.设置cookie生效时间
			cookiesname.setMaxAge(60*60*24*30);
			cookiepsw.setMaxAge(60*60*24*30);
			//将cookie对象添加到本地客服端
			resp.addCookie(cookiesname);
			resp.addCookie(cookiepsw);
		}
		UserModel usermodel = ls.getUserInfor(ssid,spwt);
		HttpSession session = req.getSession();
		//将获取的信息存入session中
		session.setAttribute("usermodel", usermodel);

		int flag = ls.validateUser(usermodel);
		
		//如果返回权限为2则跳往管理员界面
		if(2==flag){
		  req.getRequestDispatcher("manger_index.jsp").forward(req, resp);
	   }
	 	//如果返回权限为1则跳往学生界面
	else if(1==flag){
		
		req.getRequestDispatcher("student_index.jsp").forward(req, resp);
		
		
	}
		
		//否则继续返回登录界面
	else{
		req.getRequestDispatcher("login.jsp").forward(req, resp);
		
	}
		
	}
}
